// 导入login
import { login, getProfile, getUserInfoByid } from '@/api/user'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'

export default {
  namespaced: true, // 命名空间
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      // 实现持久化
      setToken(token)
    },
    delToken(state) {
      state.token = ''
      removeToken()
    },
    // 获取用户
    setUserInfo(state, info) {
      state.info = info
    },
    // 删除
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 退出登录
    logout(context) {
      context.commit('delToken')
      context.commit('delUserInfo')
    },
    async  setUserInfo(context) {
      try {
        const res = await getProfile()
        console.log(res, 'setUserInfo--------')

        const info = await getUserInfoByid(res.data.userId)
        console.log(info, 'getUserInfoByid')
        context.commit('setUserInfo', res.data)
      } catch (error) {
        console.log(error, '获取用户信息失败')
      }
    },
    async   userLogin(context, formData) {
      // console.log(context, 'context')
      // 发送实现登录 获取token 存储到vuex中
      const res = await login(formData)
      // console.log(res, 'res')
      context.commit('setToken', res.data)
      setTimeStamp()
    }
  }
}

